package edu.ynu.se.xiecheng.achitectureclass.project.service;

import edu.ynu.se.xiecheng.achitectureclass.project.dao.CaptureImageDAO;
import edu.ynu.se.xiecheng.achitectureclass.project.po.dto.YsCaptureResponse;
import edu.ynu.se.xiecheng.achitectureclass.project.po.entity.CaptureImage;
import edu.ynu.se.xiecheng.achitectureclass.project.utils.OssUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import java.util.*;

@Service
@Slf4j
public class YsCaptureService {
    private static final String YS_CAPTURE_URL = "https://open.ys7.com/api/lapp/device/capture";

    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private OssUtils ossUtils;

    @Autowired
    private CaptureImageDAO captureImageDAO;

    public Map<String, Object> capture(String accessToken) {
        try {
            MultiValueMap<String, String> params = new LinkedMultiValueMap<>();
            params.add("accessToken", accessToken);
            params.add("deviceSerial", "L29334649");
            params.add("channelNo", "1");
            params.add("quality", "1");

            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);

            HttpEntity<MultiValueMap<String, String>> requestEntity =
                    new HttpEntity<>(params, headers);

            ResponseEntity<YsCaptureResponse> response = restTemplate.postForEntity(
                    YS_CAPTURE_URL,
                    requestEntity,
                    YsCaptureResponse.class
            );

            if (response.getStatusCode().is2xxSuccessful() &&
                    "200".equals(response.getBody().getCode())) {
                String ysImageUrl = response.getBody().getData().getPicUrl();
                String imageUrl = ossUtils.uploadImage(ysImageUrl);

                // 保存图片信息到数据库
                CaptureImage captureImage = new CaptureImage();
                captureImage.setImageUrl(imageUrl);
                captureImage.setTimestamp(new Date());
                captureImageDAO.save(captureImage);

                Map<String, Object> result = new HashMap<>();
                result.put("picUrl", imageUrl);
                result.put("time", captureImage.getTimestamp().toString());
                return result;
            } else {
                log.error("Failed to capture: {}", response.getBody().getMsg());
                throw new RuntimeException("Failed to capture");
            }
        } catch (Exception e) {
            log.error("Error capturing", e);
            throw new RuntimeException("Error capturing", e);
        }
    }

    public List<CaptureImage> getRecentImages(int limit) {
        try {
            List<CaptureImage> images = captureImageDAO.findTopByOrderByTimestampDesc(limit);
            log.info("Retrieved {} images from database", images.size());
            return images;
        } catch (Exception e) {
            log.error("获取图片错误", e);
            return new ArrayList<>();
        }
    }
}